package ui.activity.profit;

import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import net.ck.hzq.R;
import net.ck.hzq.TobuyApplication;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import Utils.SharedPrefStore;
import base.BaseAct;
import base.BaseBiz;
import base.BaseFra;
import butterknife.BindView;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;
import event.HiddenOpenEvent;
import event.NetErrorEvent;
import event.SetUpdateEvent;
import ui.activity.profit.biz.ProfitBiz;
import ui.activity.profit.component.DaggerProfitComponent;
import ui.activity.profit.contract.ProfitContract;
import ui.activity.profit.module.ProfitModule;
import ui.activity.profit.presenter.ProfitPresenter;
import ui.adapter.FragAdp;
import ui.fragment.TodayMoneyCrahFra;
import ui.fragment.TodayMoneyExpandFra;
import ui.fragment.TodayMoneyPromotionFra;
import ui.model.ProfitBean;
import ui.model.ProfitNewBean;
import ui.model.TodyBean;
import util.AlertUtils;
import util.SysUtils;
import widget.tab.TabPageIndicator;


/**
 * 收益界面
 * Created by admin on 2017/8/4.
 */

public class ProfitAct extends BaseAct implements ProfitContract.View {


    @Inject
    ProfitPresenter presenter;
    @Inject
    ProfitBiz biz;

    @BindView(R.id.my_tabs)
    TabPageIndicator myTab;
    @BindView(R.id.my_vp)
    ViewPager vp;
    public List<BaseFra> fragments;
    List<String> titles = new ArrayList<>();
    @BindView(R.id.profit_day)
    TextView daytxt;
    @BindView(R.id.profit_check)
    TextView check;

    @BindView(R.id.item_profit_total_amount)
    TextView amount;
    @BindView(R.id.item_profit_divided_income)
    TextView income;
    @BindView(R.id.item_profit_active_reward)
    TextView reward;
    @BindView(R.id.item_profit_active_merchant)
    TextView merchant;
    @BindView(R.id.totalnum)
    TextView totalnum;
    @BindView(R.id.item_profit_num1)
    TextView item_profit_num1;
    @BindView(R.id.item_profit_num2)
    TextView item_profit_num2;
    @BindView(R.id.item_profit_num3)
    TextView item_profit_num3;
    @BindView(R.id.item_profit_num4)
    TextView item_profit_num4;
    @BindView(R.id.item_profit_name1)
    TextView item_profit_name1;
    @BindView(R.id.item_profit_name2)
    TextView item_profit_name2;
    @BindView(R.id.item_profit_name3)
    TextView item_profit_name3;
    @BindView(R.id.item_profit_name4)
    TextView item_profit_name4;
    @BindView(R.id.parent_view)
    LinearLayout parentView;
    @BindView(R.id.pull_refresh_ptr)
    PtrClassicFrameLayout ptr;

    @BindView(R.id.appbarlayout)
    AppBarLayout appbarlayout;
    @BindView(R.id.coordinatorLayout)
    CoordinatorLayout coordinatorLayout;

    SharedPrefStore store;

    private int year;
    private int month;
    private int day;
    private AlphaAnimation mShowAnim, mHiddenAmin;//控件的显示和隐藏动画
    long selectTime;

    @Override
    protected void setRoot() {
//        setTitleBar("#0CA6F0");
        setContentView(R.layout.activity_profit);
    }

    @Override
    protected void setup() {
        DaggerProfitComponent.builder().profitModule(new ProfitModule(this)).build().inject(this);
        setToolBar(getResources().getString(R.string.lang_day_profit), "");
        presenter.setBiz(biz);
        //控件显示的动画
        mShowAnim = new AlphaAnimation(0.0f, 1.0f);
        mShowAnim.setDuration(300);

        //控件隐藏的动画
        mHiddenAmin = new AlphaAnimation(1.0f, 0.0f);
        mHiddenAmin.setDuration(300);
    }


    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        selectTime = System.currentTimeMillis();
        fragments = new ArrayList<>();
        daytxt.setText(SysUtils.sf4.format(new Date(System.currentTimeMillis())));
        store = new SharedPrefStore();
        titles.add("团队分润");
        titles.add("直营分润");
        titles.add("激活奖励");
        fragments.add(new TodayMoneyPromotionFra());
        fragments.add(new TodayMoneyExpandFra());
        fragments.add(new TodayMoneyCrahFra());
        vp.setPageMargin(SysUtils.dip2px(this, 0f));
        vp.setOffscreenPageLimit(titles.size());
        vp.setAdapter(new FragAdp(this.getSupportFragmentManager(), titles, fragments));
        myTab.setViewPager(vp);
        setTabPagerIndicator();
        RxView.touches(daytxt)
                .compose(this.<MotionEvent>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(MotionEvent -> {
                    TimePickerDialog timePickerDialog = AlertUtils.timePicker2(ProfitAct.this, 365 * 5, 0, selectTime, new OnDateSetListener() {
                        @Override
                        public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                            selectTime = millseconds;
                            daytxt.setText(SysUtils.sf4.format(new Date(millseconds)));
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTimeInMillis(millseconds);
                             year = calendar.get(Calendar.YEAR);
                             month = calendar.get(Calendar.MONTH) + 1;
                             day = calendar.get(Calendar.DAY_OF_MONTH);
//                            presenter.getTopInfo(year, month, day);
//                            EventBus.getDefault().post(new SetUpdateEvent(year, month, day));
                        }
                    });
                    timePickerDialog.show(ProfitAct.this.getSupportFragmentManager(), "all");
                });

        RxView.clicks(check)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> {
                    presenter.getTopInfo(year, month, day);
                    EventBus.getDefault().post(new SetUpdateEvent(year, month, day));
                } );
//        presenter.getInfo(false, TobuyApplication.getCustomId(), day.getText().toString().trim());
        Calendar calendar = Calendar.getInstance();
//获取系统的日期
//年
         year = calendar.get(Calendar.YEAR);
//月
         month = calendar.get(Calendar.MONTH) + 1;
//日
         day = calendar.get(Calendar.DAY_OF_MONTH);
        presenter.getTopInfo(year, month, day);

        ptr.setLastUpdateTimeRelateObject(this);
        ptr.disableWhenHorizontalMove(true);
        ptr.setEnabled(false);
        ptr.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                presenter.getTopInfo(year, month, day);
                EventBus.getDefault().post(new SetUpdateEvent(year, month, day));
                appbarlayout.setExpanded(true);
                gettoday();
            }
        });
        coordinatorLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if( isVisibleLocal(appbarlayout)){
                    ptr.setEnabled(true);
                }else{
                    ptr.setEnabled(false);
                }
                return false;
            }
        });

        gettoday();
    }

    private void gettoday(){
        biz.GetTodyInfo(new BaseBiz.Callback<List<TodyBean>>() {
            @Override
            public void onSuccess(List<TodyBean> todyBeans) {
                int total = todyBeans.get(0).getCount()+todyBeans.get(1).getCount()+todyBeans.get(2).getCount()+todyBeans.get(3).getCount();
                item_profit_num1.setText(todyBeans.get(0).getCount()+"");
                item_profit_num2.setText(todyBeans.get(1).getCount()+"");
                item_profit_num3.setText(todyBeans.get(2).getCount()+"");
                item_profit_num4.setText(todyBeans.get(3).getCount()+"");
                item_profit_name1.setText(todyBeans.get(0).getLabel()+"");
                item_profit_name2.setText(todyBeans.get(1).getLabel()+"");
                item_profit_name3.setText(todyBeans.get(2).getLabel()+"");
                item_profit_name4.setText(todyBeans.get(3).getLabel()+"");

                totalnum.setText(total+"");

            }

            @Override
            public void onFailure(List<TodyBean> todyBeans) {

            }
        });
    }
    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        biz.onDestory();
    }

    //当 View 有一点点不可见时立即返回false!
    public static boolean isVisibleLocal(View target){
        Rect rect =new Rect();
        target.getLocalVisibleRect(rect);
        return rect.top==0;
    }
    @Override
    public void upDateUI(ProfitBean bean) {
    }

    @Override
    public void upDateTopUI(ProfitNewBean bean) {
        amount.setText(bean.getTotalAmount());
        income.setText(bean.getDividedIncome());
        reward.setText(bean.getActiveReward());
        merchant.setText(bean.getActiveMerchant());
        ptr.onRefreshComplete();
        appbarlayout.setExpanded(true);
    }

    /**
     * 设置标题栏
     */
    private void setTabPagerIndicator() {
        myTab.setIndicatorMode(TabPageIndicator.IndicatorMode.MODE_NOWEIGHT_EXPAND_SAME);// 设置模式，一定要先设置模式
//        myTab.setDividerColor(Color.parseColor("#0099E6"));// 设置分割线的颜色
        myTab.setDividerPadding(SysUtils.dip2px(TobuyApplication.getInstance(), 0));
        myTab.setIndicatorColor(Color.parseColor("#0099E6"));// 设置底部导航线的颜色
        myTab.setTextColorSelected(Color.parseColor("#0099E6"));// 设置tab标题选中的颜色
        myTab.setTextColor(Color.parseColor("#333333"));// 设置tab标题未被选中的颜色
        myTab.setTextSize((int) SysUtils.sp2px(TobuyApplication.getInstance(), 14));// 设置字体大小
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerCancelOrder(HiddenOpenEvent event) {
        if( isVisibleLocal(appbarlayout)){
            ptr.setEnabled(true);
        }else{
            ptr.setEnabled(false);
        }
    }
}
